<template>
  <AdminPage
    title="商品管理"
    :filters="filters"
    :pagination-enabled="true"
    v-model:page="page"
    :total="total"
    :page-size="pageSize"
  >
            <!-- 0-待审核，1-已上架，2-已下架，3-审核未通过 -->

    <!-- 筛选栏 -->
    <template #filters>
      <el-form-item label="商品编号" class="filter-item">
        <el-input v-model="filters.id" placeholder="请输入" clearable size="small" />
      </el-form-item>
      <el-form-item label="商品名称" class="filter-item">
        <el-input v-model="filters.name" placeholder="请输入" clearable size="small" />
      </el-form-item>
      <el-form-item label="状态" class="filter-item">
        <el-select v-model="filters.status" placeholder="请选择" clearable size="small">
          <el-option label="待审核" :value="0" />
          <el-option label="已上架" :value="1" />
          <el-option label="已下架" :value="2" />
          <el-option label="审核未通过" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" class="filter-item">
        <el-input v-model="filters.category" placeholder="请输入" clearable size="small" />
      </el-form-item>
      <el-form-item label="品牌" class="filter-item">
        <el-input v-model="filters.brand" placeholder="请输入" clearable size="small" />
      </el-form-item>
      
      
      <el-form-item class="filter-item">
        <el-button type="primary" :icon="Search" @click="handleSearch" size="small">搜索</el-button>
        <el-button @click="handleReset" size="small">重置</el-button>
      </el-form-item>
    </template>

    <!-- 表格 -->
    <template #table>
      <el-table :data="pageData" border stripe header-cell-class-name="table-header" class="list-table">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="id" label="商品编号" min-width="100" />
        <el-table-column prop="image" label="图片" min-width="100">
          <template #default="{ row }">
            <div class="image-container">
              <img :src="row.image" alt="商品图片" class="product-image">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌" min-width="100" />

        <!-- <el-table-column prop="isUserAddCategory" label="是否由用户填写" min-width="180" /> -->
        <!-- 0-待审核，1-已上架，2-已下架，3-审核未通过 -->
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="row.status === 1" type="success">已上架</el-tag>
            <el-tag v-else-if="row.status === 2" type="info">已下架</el-tag>
            <el-tag v-else-if="row.status === 3" type="danger">审核未通过</el-tag>
            <el-tag v-else type="info">未知状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="pageData.some(item => item.status === 0)">
          <template #default="{ row }">
            <div class="operation-buttons" v-if="row.status===0">
              <el-button 
                type="success" 
                size="small"
                class="agree-button"
                @click="handleAgreeProduct(row.id)"
              >
                同意
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                class="refuse-button"
                @click="handleRefuseProduct(row.id)"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
       
        <el-table-column label="介绍" width="120">
          <template #default="{row}">
            <el-link type="primary" size="small"
              @click="handleViewDetail(row)"
              style="margin-right: 0.5rem;">查看详情</el-link>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 分页器 -->
    <template #pagination></template>
  </AdminPage>

  <!-- 拒绝商品理由对话框 -->
  <el-dialog
    v-model="refuseDialogVisible"
    title="拒绝商品上架"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="refuseForm" label-width="80px">
      <el-form-item label="拒绝理由" required>
        <el-input
          v-model="refuseForm.reason"
          type="textarea"
          :rows="4"
          placeholder="请输入拒绝该商品上架的理由..."
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="refuseDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmRefuseProduct" :loading="refuseLoading">
          确认拒绝
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 商品详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="商品详情"
    width="500px"
    height="500px"
    overflow="auto"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div v-if="selectedProduct" class="product-detail">
      <!-- 商品头部信息 -->
      <div class="product-header">
        <div class="product-image-container">
          <img 
            :src="selectedProduct.image" 
            :alt="selectedProduct.name" 
            class="product-image"
          />
        </div>
        <div class="product-main-info">
          <div class="product-name-section">
            <h5 class="product-name">**{{ selectedProduct.name }}**</h5>
            <div class="price-info">
              <span class="price-value">¥{{ selectedProduct.price }}</span>
              <span class="price-unit">元</span>
            </div>
          </div>
          
          <!-- ID位置不变，状态和创建时间靠右显示 -->
          <div class="id-status-row">
            <div class="product-id">商家ID：{{ selectedProduct.merchantId}}</div>
            <div class="right-info">
              <div class="status-badge">
                <el-tag v-if="selectedProduct.status === 0" type="warning">待审核</el-tag>
                <el-tag v-else-if="selectedProduct.status === 1" type="success">已上架</el-tag>
                <el-tag v-else-if="selectedProduct.status === 2" type="info">已下架</el-tag>
                <el-tag v-else-if="selectedProduct.status === 3" type="danger">审核未通过</el-tag>
                <el-tag v-else type="info">未知状态</el-tag>
              </div>
            </div>
          </div>
          
          <div class="createTime right-aligned">创建时间：{{ selectedProduct.createTime }}</div>
        </div>
      </div>

      <!-- 商品基本属性 -->
      <div class="product-attributes">
        <h3 class="section-title">基本属性</h3>
        <div class="attributes-grid">
          <div class="attribute-item">
            <span class="attribute-label">分类：</span>
            <span class="attribute-value">{{ selectedProduct.category }} | 品牌：{{ selectedProduct.brand }}</span>
          </div>
          
          <div class="stock-info">
            <span class="info-label">库存：</span>
            <span class="stock-value">{{ selectedProduct.stock }}件</span>
          </div>
          
          <div class="attribute-item">
            <span class="attribute-label">规格：</span>
            <div class="spec-details">
              <template v-if="isJson(selectedProduct.spec)">
                <div v-for="(value, key) in parseJson(selectedProduct.spec)" :key="key" class="spec-item">
                  {{ key }}：{{ value }}
                </div>
              </template>
              <template v-else>
                {{ selectedProduct.spec || '无' }}
              </template>
            </div>
          </div>
          
          <div class="sold-info">
            <span>已售：</span>
            <span>{{ selectedProduct.sold }}件</span>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false" class="close-button">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import {  AgreeProductService, RefuseProductService, getItemsByStateAndName } from '../../api/admin'
import { ElMessage } from 'element-plus'
import AdminPage from '../../components/admin/AdminPage.vue'


type Product = {
  id: number
  merchantId:number
  name: string
  price: number
  category: string
  createTime: string
  stock: number
  status: number
  image:string
  brand:string
  spec:string
  sold:number
  commentCount:number
 isUserAddCategory:number
}

const filters = reactive({
    id: '',
  name: '', 
  category: '',
  status: '',
  brand: '' // 新增品牌筛选
})

const allData = ref<Product[]>([])

// 拒绝商品对话框相关
const refuseDialogVisible = ref(false)

// 判断是否为JSON字符串
const isJson = (str: string) => {
  if (!str) return false
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

// 解析JSON字符串
const parseJson = (str: string) => {
  try {
    return JSON.parse(str)
  } catch (e) {
    return {}
  }
}
const refuseLoading = ref(false)
const refuseForm = reactive({
  reason: '',
  id: null as number | null
})

// 商品详情对话框相关
const detailDialogVisible = ref(false)
const selectedProduct = ref<Product | null>(null)

// 拒绝商品上架
const handleRefuseProduct = (id: number) => {
  refuseForm.id = id
  refuseForm.reason = ''
  refuseDialogVisible.value = true
}

// 查看商品详情
const handleViewDetail = (product: Product) => {
  selectedProduct.value = product
  detailDialogVisible.value = true
}

// 确认拒绝商品
const confirmRefuseProduct = async () => {
  if (!refuseForm.reason.trim()) {
    ElMessage.warning('请输入拒绝理由')
    return
  }
  
  if (!refuseForm.id) {
    ElMessage.error('商品ID不能为空')
    return
  }

  try {
    refuseLoading.value = true
    console.log('拒绝商品上架，商品ID:', refuseForm.id, '理由:', refuseForm.reason)
    await RefuseProductService(refuseForm.id, refuseForm.reason)
    ElMessage.success('拒绝商品上架成功')
    allData.value = allData.value.filter(item => item.id !== refuseForm.id)
    refuseDialogVisible.value = false
  } catch (error) {
    console.error('拒绝商品上架失败:', error)
    ElMessage.error('拒绝商品上架失败')
  } finally {
    refuseLoading.value = false
  }
}

// 统一的数据获取函数，只使用getItemsByStateAndName接口
const fetchProducts = async () => {
  try {
    // 获取当前筛选条件
    const currentStatus = filters.status !== '' && filters.status !== null && filters.status !== undefined 
      ? Number(filters.status) 
      : status.value
    
    const res = await getItemsByStateAndName(
      page.value, 
      pageSize.value, 
      currentStatus,
      filters.category || '',
      filters.name || '',
      filters.brand || ''
    )
    
    console.log('商品列表数据:', res.data)
    
    if (res && res.data && res.data.items) {
      // 修复id属性的映射，确保表格能正确显示数据
      allData.value = res.data.items.map((item: any) => ({
        id: item.id,  // 确保id属性存在并正确映射
        merchantId: item.merchantId,
        productId: item.id.toString(), // 保留productId以兼容其他可能的使用
        name: item.name,
        price: item.price,
        category: item.category,
        createTime: new Date(item.createTime).toLocaleString(),
        stock: item.stock,
        status: item.status,
        image: item.image,
        brand: item.brand,
        spec: item.spec,
        sold: item.sold,
        commentCount: item.commentCount,
        isUserAddCategory: item.isUserAddCategory || 0
      }))
      
      // 设置总数
      const dataAny = res.data as any
      total.value = 
        (typeof dataAny.total === 'number' && dataAny.total) ||
        (typeof dataAny.totalCount === 'number' && dataAny.totalCount) ||
        (typeof dataAny.count === 'number' && dataAny.count) ||
        0
    } else {
      allData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败，请重试')
    allData.value = []
    total.value = 0
  }
}

onMounted(async () => {
  await fetchProducts()
})

const page = ref(1)
const pageSize = ref(8)
const status = ref(0)
const total = ref(0)
// 最大页数仅由 AdminPage 内部计算控制，这里无需再次计算
const filteredData = computed(() => {
  return allData.value.filter(row => {
    const matchId = !filters.id || row.id.toString().includes(filters.id)
    const matchName = !filters.name || row.name.includes(filters.name)
    const matchCate = !filters.category || row.category === filters.category
    const matchStatus = filters.status === '' || filters.status === null || filters.status === undefined || row.status === Number(filters.status)
    const matchBrand = !filters.brand || row.brand === filters.brand
    return matchId && matchName && matchCate && matchStatus &&  matchBrand
  })
})

const pageData = computed(() => {
  return filteredData.value
})

const handleSearch = () => {
  page.value = 1
  // 将筛选栏的状态同步到请求参数并调用接口
  if (filters.status !== '' && filters.status !== null && filters.status !== undefined) {
    status.value = Number(filters.status)
  }
  
  // 直接调用统一的数据获取函数
  fetchProducts()
}

//重置内容
const handleReset = () => {
  filters.id = ''
  filters.name = ''
  filters.category = ''
  filters.status = ''
  filters.brand = '' // 重置品牌筛选
  page.value = 1
  // 重置后使用统一的数据获取函数
  fetchProducts()
}
//同意商品上架
const handleAgreeProduct = async (productId: number) => {
  try {
    console.log('同意商品上架，商品ID:', productId)
    await AgreeProductService(productId)
    ElMessage.success('同意商品上架成功')
    allData.value = allData.value.filter(item => item.id !== productId)
  } catch (error) {
    console.error('同意商品上架失败:', error)
    ElMessage.error('同意商品上架失败')
  }
}

// 当切换状态、分页参数时，从服务端按状态拉取数据
watch(() => filters.status, (newVal) => {
  if (newVal === '' || newVal === null || newVal === undefined) return
  status.value = Number(newVal)
  page.value = 1
  
  // 直接调用统一的数据获取函数
  fetchProducts()
})

watch([page, pageSize], () => {
  // 直接调用统一的数据获取函数
  fetchProducts()
})


// 分页事件由 AdminPage 统一触发（v-model:page）
</script>

<style scoped lang="scss">
/* 拒绝商品对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.2rem;
}
.el-dialog__footer {
  padding-top: 0;
}

:deep(.el-dialog__body) {
  padding: 0.3rem;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}
    
 .operation-buttons {
          display: flex;
          flex-direction: column;
          width: 100%;
          gap: 0.2rem;
 }
 .operation-buttons .el-button {
          width: 100%;
 }
        
.operation-buttons .el-button.agree-button {
  align-self: flex-start;
}
        
.operation-buttons .el-button.refuse-button {
align-self: flex-end;
  }
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 3.125rem;
  height: 3.125rem;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品详情弹框样式 */
.product-detail {
  padding: 0.75rem 0;
}

/* 商品头部信息 */
.product-header {
  display: flex;
  gap: 1.25rem;
  margin-bottom: 1.25rem;
}

.product-image-container {
  width: 10rem;
  height: 10rem;
  border-radius: 0.5rem;
  overflow: hidden;
  background-color: #f8fafc;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 0.0625rem solid #e2e8f0;
}

.product-image {
  max-width: 8.75rem;
  max-height: 8.75rem;
  object-fit: contain;
}

.product-main-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name-section {
  margin-bottom: 0.5rem;
}

.product-name {
  font-size: 1.2rem;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 0.4rem 0;
}

.product-id {
  color: #666;
  font-size: 0.85rem;
  left:  1rem;
  position: absolute;
}

.createTime {
  color: #666;
  font-size: 0.85rem;
}

/* ID位置不变，状态和创建时间靠右显示 */
.id-status-row {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin: 0.2rem 0;
}

.right-info {
  display: flex;
  justify-content: flex-end;
  flex: 1;
}

.status-badge {
  margin-left: auto;
  text-align: right;
}

.right-aligned {
  text-align: right;
}

/* 规格详情样式 */
.spec-details {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.spec-item {
  font-size: 0.85rem;
  color: #333;
}

.status-badge {
  text-align: right;
}


.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 0.3rem 0;
  padding-bottom: 0.2rem;
  border-bottom: 0.125rem solid #f0f0f0;
}

.attributes-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.4rem;
}

.attribute-item {
  display: flex;
  align-items: flex-start;
}

.attribute-label {
  font-weight: 500;
  color: #666;
  min-width: 4.375rem;
  font-size: 0.9rem;
}

.attribute-value {
  color: #333;
  font-size: 0.9rem;
}

/* 库存和价格信息 */
.product-stock-price {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
  padding: 0.2rem;
  background-color: #f8fafc;
  border-radius: 0.5rem;
  border: 1px solid #e2e8f0;
}

.stock-info, .price-info, .total-info, .warning-info {
  display: flex;
  align-items: center;
}

.info-label, .price-unit, .total-label, .warning-label {
  color: #666;
  font-size: 0.95rem;
  // margin-right: 0.5rem;
}

.stock-value, .price-value, .total-value, .warning-value {
  color: #666;
  font-weight: 500;
  font-size: 0.95rem;
}

.price-value {
  color: #e74c3c;
  font-size: 1.8rem;
  font-weight: 700;
}

.total-value {
  color: #3498db;
  font-weight: 700;
}

/* 对话框底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

.close-button {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-header {
    flex-direction: column;
    align-items: center;
  }

  .product-image-container {
    width: 7.5rem;
    height: 7.5rem;
    margin-bottom: 0.75rem;
  }

  .product-image {
    max-width: 6.25rem;
    max-height: 6.25rem;
  }

  .attributes-grid {
    grid-template-columns: 1fr;
  }

  .dialog-footer {
    justify-content: center;
  }

  .price-value {
    font-size: 1.5rem !important;
  }
}
</style>


